package icu.guodapeng.flutter_plugin_demo

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.media.AudioManager
import androidx.annotation.NonNull
import icu.guodapeng.flutter_plugin_live.FlutterPluginDemoViewFactory
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.Registrar
import io.flutter.plugin.platform.PlatformViewRegistry

/** FlutterPluginDemoPlugin */
class FlutterPluginDemoPlugin : FlutterPlugin, MethodCallHandler {
    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        val channel = MethodChannel(flutterPluginBinding.binaryMessenger, "icu.guodapeng.flutter_plugin_demo")
        channel.setMethodCallHandler(FlutterPluginDemoPlugin())

        register(flutterPluginBinding.applicationContext, flutterPluginBinding.binaryMessenger, flutterPluginBinding.platformViewRegistry)
    }

    // This static function is optional and equivalent to onAttachedToEngine. It supports the old
    // pre-Flutter-1.12 Android projects. You are encouraged to continue supporting
    // plugin registration via this function while apps migrate to use the new Android APIs
    // post-flutter-1.12 via https://flutter.dev/go/android-project-migration.
    //
    // It is encouraged to share logic between onAttachedToEngine and registerWith to keep
    // them functionally equivalent. Only one of onAttachedToEngine or registerWith will be called
    // depending on the user's project. onAttachedToEngine or registerWith must both be defined
    // in the same class.
    companion object {
        @JvmStatic
        fun registerWith(registrar: Registrar) {
            val channel = MethodChannel(registrar.messenger(), "icu.guodapeng.flutter_plugin_demo")
            channel.setMethodCallHandler(FlutterPluginDemoPlugin())

            register(registrar.context(), registrar.messenger(), registrar.platformViewRegistry())
        }

        private fun register(context: Context, binaryMessenger: BinaryMessenger, registry: PlatformViewRegistry) {

            val eventChannel = EventChannel(binaryMessenger, "icu.guodapeng.flutter_plugin_demo/event")

            eventChannel.setStreamHandler(SwiftStreamHandler(context))

            registry.registerViewFactory("platform_text_view", FlutterPluginDemoViewFactory(binaryMessenger))
        }
    }

    override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
        when (call.method) {
            "getPlatformVersion" -> {
                result.success("Android ${android.os.Build.VERSION.RELEASE}")
            }
            "testArg" -> {
                val value: String? = call.argument("value")
                result.success("Android $value")
            }
            "testArgArr" -> {
                val value: String? = call.argument("value")
                result.success(mapOf("msg" to "Android $value"))
            }
            else -> {
                result.notImplemented()
            }
        }
    }

    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
    }
}

private const val VOLUME_CHANGED_ACTION = "android.media.VOLUME_CHANGED_ACTION"

private class SwiftStreamHandler(var context: Context) : EventChannel.StreamHandler {

    override fun onListen(o: Any?, eventSink: EventChannel.EventSink) {
        val filter = IntentFilter()
        filter.addAction(VOLUME_CHANGED_ACTION)
        context.registerReceiver(object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                if (intent.action == VOLUME_CHANGED_ACTION) {

                    val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
                    val max = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC).toFloat()
                    val vol = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC).toFloat()

                    val event: MutableMap<String, Any> = mutableMapOf()
                    event["e"] = "vol"
                    event["v"] = vol / max
                    event["t"] = AudioManager.STREAM_MUSIC

                    eventSink.success(event)
                }
            }
        }, filter)
    }

    override fun onCancel(o: Any?) {
        println("flutter_plugin_demo onCancel")
    }
}